package com.wdc.deliveryrobot.fragment;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sirui.selfstudysdk.main.SelfChassisState;
import com.wdc.deliveryrobot.R;
import com.wdc.deliveryrobot.activity.BaseActivity;
import com.wdc.deliveryrobot.activity.DeliveryActivity;
import com.wdc.deliveryrobot.adapter.CruiseMoreAdapter;
import com.wdc.deliveryrobot.adapter.CruisePointAdapter;
import com.wdc.deliveryrobot.adapter.CruiseSelectAdapter;
import com.wdc.deliveryrobot.adapter.CruiseSumAdapter;
import com.wdc.deliveryrobot.adapter.PointListAdapter;
import com.wdc.deliveryrobot.decoration.SpaceItemDecoration;
import com.wdc.deliveryrobot.decoration.SpaceLeftDecoration;
import com.wdc.deliveryrobot.model.Line;
import com.wdc.deliveryrobot.model.Point;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: tianHuiDa
 * @Date: 2024/11/16
 * @Description: 巡航fragment
 */
public class CruiseFragment extends Fragment implements View.OnClickListener,CruiseSumAdapter.OnItemClickListener,CruisePointAdapter.OnItemClickListener, CruiseSelectAdapter.OnItemClickListener {

    private LinearLayout linearLayoutReturn,linearLayoutEnd,linearLayoutStartTask,linearLayoutSaveLine,linearLayoutCharge,linearLayoutRecycling;

    private RecyclerView recyclerView,recyclerViewPoint,recyclerViewSelect,recyclerViewPointMore;

    private ImageView imageViewCharge,imageViewRecycling,imageView;

    private TextView textViewNameMore,textViewStopTimeMore,textViewCruiseSumMore;

    private EditText editTextTaskName,editTextStopTime,editTextCruiseSum;
    private CruiseSumAdapter cruiseSumAdapter;

    private CruisePointAdapter cruisePointAdapter;

    private CruiseSelectAdapter cruiseSelectAdapter;

    private CruiseMoreAdapter cruiseMoreAdapter;

    private DrawerLayout drawerLayout;

    private SelfChassisState selfChassisState;

    private Line line,lineSelect;

    private List<Line> lineList = new ArrayList<>();

    private List<String> pointList = new ArrayList<>();

    private List<String> selectList = new ArrayList<>();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 加载 Fragment 的布局
        View view = inflater.inflate(R.layout.fragment_cruise, container, false);

        init(view);

        setData();
        return view;
    }


    public void init(View view){
        linearLayoutReturn = view.findViewById(R.id.return_back);
        linearLayoutEnd = view.findViewById(R.id.drawer1);
        linearLayoutStartTask = view.findViewById(R.id.start_task);
        linearLayoutSaveLine = view.findViewById(R.id.save_line);
        linearLayoutCharge = view.findViewById(R.id.charge_point);
        linearLayoutRecycling = view.findViewById(R.id.recycling_point);

        imageViewCharge = view.findViewById(R.id.statue_charge);
        imageViewRecycling = view.findViewById(R.id.statue_recycling);
        imageView = imageViewCharge;

        editTextTaskName = view.findViewById(R.id.task_name);
        editTextStopTime = view.findViewById(R.id.stop_time);
        editTextCruiseSum = view.findViewById(R.id.cruise_sum);

        drawerLayout = view.findViewById(R.id.drawer_layout);
        recyclerView = view.findViewById(R.id.cruiseData);
        recyclerViewPoint = view.findViewById(R.id.point_list);
        recyclerViewSelect = view.findViewById(R.id.select_list);
        recyclerViewPointMore = view.findViewById(R.id.recycling_point_more);

        textViewNameMore = view.findViewById(R.id.name_more);
        textViewCruiseSumMore = view.findViewById(R.id.cruise_sum_more);
        textViewStopTimeMore = view.findViewById(R.id.stop_time_more);

        List<String> test1 = new ArrayList<>();
        test1.add("1");
        test1.add("2");
        test1.add("3");
        List<String> test2 = new ArrayList<>();
        test2.add("1");
        test2.add("2");
        test2.add("3");
        test2.add("2");
        test2.add("3");
        lineList.add(new Line("test","普通","10","1",test1));
        lineList.add(new Line("test1","普通","10","1",test2));

        cruiseSumAdapter = new CruiseSumAdapter(lineList,getContext(),this);

        if (selfChassisState != null){
            //获取点位数据
            JSONObject jsonObject = selfChassisState.getStations();
            JSONArray jsonArray = jsonObject.getJSONArray("point");
            if (jsonArray != null){
                for (int i = 0;i < jsonArray.size();i ++){
                    if (jsonArray.getJSONObject(i).getString("mapName").equals(selfChassisState.getMapName())){
                        pointList.add(jsonArray.getJSONObject(i).getString("name"));
                    }
                }
            }
        }
        cruisePointAdapter = new CruisePointAdapter(pointList,this);

        cruiseSelectAdapter = new CruiseSelectAdapter(this,selectList);


        linearLayoutReturn.setOnClickListener(this);
        linearLayoutStartTask.setOnClickListener(this);
        linearLayoutSaveLine.setOnClickListener(this);
        linearLayoutRecycling.setOnClickListener(this);
        linearLayoutCharge.setOnClickListener(this);

        //禁止滑动或者点击关闭打开抽屉
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        // 添加抽屉监听器
        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                // 禁用滑动操作
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                if (line != null){
                    Log.d("thd_","打开抽屉数据:" + line);
                }
                recyclerViewPointMore.setAdapter(cruiseMoreAdapter);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                // 可以做些额外的操作

            }

            @Override
            public void onDrawerStateChanged(int newState) {
                // 监听状态变化
            }
        });

    }

    public void setData(){
        //设置布局管理器

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new SpaceItemDecoration(5));
        recyclerView.setAdapter(cruiseSumAdapter);

        // 设置 GridLayoutManager，4 列
        recyclerViewPoint.setLayoutManager(new LinearLayoutManager(getContext()));
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 4);
        recyclerViewPoint.setLayoutManager(gridLayoutManager);
        recyclerViewPoint.addItemDecoration(new SpaceItemDecoration(5));
        recyclerViewPoint.setAdapter(cruisePointAdapter);

        //选中
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        recyclerViewSelect.setLayoutManager(linearLayoutManager);
        recyclerViewSelect.addItemDecoration(new SpaceLeftDecoration(10));
//        GridLayoutManager gridLayoutManagerSelect = new GridLayoutManager(getContext(), Integer.MAX_VALUE);
//        recyclerViewSelect.setLayoutManager(gridLayoutManagerSelect);
        recyclerViewSelect.setAdapter(cruiseSelectAdapter);


        //详情
        recyclerViewPointMore.setLayoutManager(new LinearLayoutManager(getContext()));
        GridLayoutManager gridLayoutManagerMore = new GridLayoutManager(getContext(), 1);
        recyclerViewPointMore.setLayoutManager(gridLayoutManagerMore);
        recyclerViewPointMore.addItemDecoration(new SpaceItemDecoration(5));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.return_back:
                if (getActivity() != null){
                    ((DeliveryActivity)getActivity()).switchToFragment();
                }
                break;
            case R.id.start_task:
                if (lineSelect == null){
                    //语音提示
                    Toast.makeText(getContext(),"请选中巡航路线",Toast.LENGTH_SHORT).show();
                }else {
                    //开始巡航
                    Toast.makeText(getContext(),"我开始巡航",Toast.LENGTH_SHORT).show();
                    Log.d("thd_","开始巡航,路线名称:" + lineSelect.getName());
                }
                break;
            case R.id.save_line:
                //路线保存
                if (!isNull()){
                    Toast.makeText(getContext(),"请先选择相关信息",Toast.LENGTH_SHORT).show();
                }else {
                    boolean isNow = false;
                    if (lineList != null && lineList.size() > 0){
                        for (int i = 0;i < lineList.size();i ++){
                            if (lineList.get(i).getName().equals(editTextTaskName.getText().toString())){
                                Toast.makeText(getContext(),"点位名称存在，请修改",Toast.LENGTH_SHORT).show();
                                isNow = true;
                            }
                        }
                    }
                    if (!isNow){
                        lineList.add(new Line(editTextTaskName.getText().toString(),"普通",editTextStopTime.getText().toString(),editTextCruiseSum.getText().toString(),selectList));
                        cruiseSumAdapter.setLineList(lineList);
                        recyclerView.setAdapter(cruiseSumAdapter);

                        selectList = new ArrayList<>();
                        cruiseSelectAdapter.setListSelect(selectList);
                        recyclerViewSelect.setAdapter(cruiseSelectAdapter);
                    }



                }
                break;
            case R.id.charge_point:
                imageViewCharge.setImageResource(R.drawable.selecting);
                imageViewRecycling.setImageResource(R.drawable.noselect);
                imageView = imageViewCharge;
                break;
            case R.id.recycling_point:
                imageViewCharge.setImageResource(R.drawable.noselect);
                imageViewRecycling.setImageResource(R.drawable.selecting);
                imageView = imageViewCharge;
                break;

        }
    }

    public boolean isNull(){
        if (editTextTaskName == null || editTextTaskName.equals(""))
            return false;
        if (editTextStopTime == null || editTextStopTime.equals("") || !isNumber(editTextStopTime.getText().toString()))
            return false;
        if (editTextCruiseSum == null || editTextCruiseSum.equals("") || !isNumber(editTextCruiseSum.getText().toString()) || Integer.parseInt(editTextCruiseSum.getText().toString()) == 0)
            return false;
        if (selectList == null || selectList.size() < 1)
            return false;
        if (imageView == null)
            return false;

        return true;
    }

    public boolean isNumber(String str) {
        // 正则表达式，匹配整数或浮点数，支持负号和小数点
        String regex = "^[-+]?\\d*(\\.\\d+)?$";
        return str.matches(regex);
    }

    //显示详情
    @Override
    public void showPoint(Line lines) {
        Log.d("thd_","获取到详情数据" + lines);
        cruiseMoreAdapter = new CruiseMoreAdapter(lines.getPointList());
        textViewNameMore.setText(lines.getName());
        textViewCruiseSumMore.setText(lines.getSum());
        textViewStopTimeMore.setText(lines.getTime());
        //先关闭再打开
        drawerLayout.closeDrawer(linearLayoutEnd);
        line = lines;
        drawerLayout.openDrawer(linearLayoutEnd);
    }

    //删除路线
    @Override
    public void deleteData(Line lines) {
        Log.d("thd_","删除数据:" + lines);
        for (int i = 0;i < lineList.size();i ++){
            if (lineList.get(i).getName().equals(lines.getName())){
                //删除数据
                lineList.remove(i);
                break;
            }
        }
        cruiseSumAdapter.setLineList(lineList);
        recyclerView.setAdapter(cruiseSumAdapter);
        Log.d("thd_","删除成功");
    }

    //选中路线
    @Override
    public void selectLine(Line lines) {
        this.lineSelect = lines;
    }

    @Override
    public void clickButton(String name) {
        //获取到选中的按钮,更新下方点位
        Log.d("thd_","点击按钮:" + name);
        if (selectList != null && selectList.size() > 0){
            if (selectList.get(selectList.size() - 1).equals(name)){
                Toast.makeText(getContext(),"前一个点位相同，请重新选择",Toast.LENGTH_SHORT).show();
            }else {
                selectList.add(name);
                cruiseSelectAdapter.setListSelect(selectList);
                recyclerViewSelect.setAdapter(cruiseSelectAdapter);
            }
        }else {
            selectList.add(name);
            cruiseSelectAdapter.setListSelect(selectList);
            recyclerViewSelect.setAdapter(cruiseSelectAdapter);
        }


    }

    public void setSelfChassisState(SelfChassisState selfChassisState){
        this.selfChassisState = selfChassisState;
        pointList = new ArrayList<>();
        lineList = new ArrayList<>();
        selectList = new ArrayList<>();
    }

    @Override
    public void delete(String name) {
        //删除选中的点位
        Log.d("thd_","删除点位" + name);
    }


}
